package com.gage.controller.base;

import java.text.SimpleDateFormat;
import java.util.Date;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.plugins.Page;
import com.gage.commons.result.PageInfo;
import com.gage.commons.result.Result;
import com.gage.model.shiro.ShiroUser;
import com.gage.commons.utils.StringEscapeEditor;

/**
 * @description：基础 controller
 * @author：kairu.lu
 * @date：2015/10/1 14:51
 */
public abstract class BaseController {
    // 控制器本来就是单例，这样似乎更加合理
    protected Logger logger = LogManager.getLogger(getClass());

    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        /**
         * 自动转换日期类型的字段格式
         */
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
        /**
         * 防止XSS攻击
         */
        binder.registerCustomEditor(String.class, new StringEscapeEditor());
    }

    /**
     * 获取当前登录用户对象
     * @return {ShiroUser}
     */
    public ShiroUser getShiroUser() {
        return (ShiroUser) SecurityUtils.getSubject().getPrincipal();
    }

    /**
     * 获取当前登录用户id
     * @return {Long}
     */
    public Long getUserId() {
        return this.getShiroUser().getId();
    }
	public Integer getAssociationId() {
		return this.getShiroUser().getAssociationId();
	}
	public Integer getDepartmentId() {
		return this.getShiroUser().getDepartmentId();
	}
	public Integer getUserType() {
		return this.getShiroUser().getUserType();
	}
    /**
     * 获取当前登录用户名
     * @return {String}
     */
    public String getStaffName() {
        return this.getShiroUser().getName();
    }

    /**
     * ajax失败
     * @param msg 失败的消息
     * @return {Object}
     */
    public Object renderError(String msg) {
        Result result = new Result();
        result.setMsg(msg);
        return result;
    }
    
    /**
     * bean validation异常
     * 
     * 此处只是粗略的构造了错误信息，只处理了第一条错误。
     * 
     * 如果要做的完美，需要将所有的错误信息展示于页面。
     * 
     * @param result
     * @return
     */
    public Object renderError(BindingResult result) {
        FieldError error = result.getFieldError();
        StringBuilder errorMsg = new StringBuilder(100);
        errorMsg.append("$(form).find(\"[name=\\\"");
        errorMsg.append(error.getField());
        errorMsg.append("\\\"]\").closest(\"td\").prev().text() + \"，");
        errorMsg.append(error.getDefaultMessage());
        errorMsg.append("\"");
        return renderError(errorMsg.toString());
    }
    
    /**
     * ajax成功
     * @return {Object}
     */
    public Object renderSuccess() {
        Result result = new Result();
        result.setSuccess(true);
        return result;
    }
    
    /**
     * ajax成功
     * @param msg 消息
     * @return {Object}
     */
    public Object renderSuccess(String msg) {
        Result result = new Result();
        result.setSuccess(true);
        result.setMsg(msg);
        return result;
    }

    /**
     * ajax成功
     * @param obj 成功时的对象
     * @return {Object}
     */
    public Object renderSuccess(Object obj) {
        Result result = new Result();
        result.setSuccess(true);
        result.setObj(obj);
        return result;
    }
    /**
     * ajax成功
     * @param obj 成功时的对象
     * @return {Object}
     */
    public Object renderSuccess(boolean success,String msg,Object o) {
        Result result = new Result();
        result.setSuccess(success);
        result.setObj(o);
        return result;
    }
    /**
     * 返回json
     * @param success
     * @param msg
     * @param status
     * @return
     */
	public String resultJson(String success, String msg, String status) {

		// 创建JSONObject对象
		JSONObject json = new JSONObject();
		// 向json中添加数据
		json.put("success", success);
		json.put("msg", msg);
		json.put("status", status);

		System.out.println(json);
		return json.toString();
	}
    public <T> Page<T> getPage(int current, int size, String sort, String order){
        Page<T> page = new Page<T>(current, size, sort);
        if ("desc".equals(order)) {
            page.setAsc(false);
        } else {
            page.setAsc(true);
        }
        return page;
    }
    
    public <T> PageInfo pageToPageInfo(Page<T> page) {
        PageInfo pageInfo = new PageInfo();
        pageInfo.setRows(page.getRecords());
        pageInfo.setTotal(page.getTotal());
        pageInfo.setOrder(page.getOrderByField());
        return pageInfo;
    }
    protected ModelAndView ajaxJson(String jsonString) {
		ModelAndView mav = new ModelAndView("jsonData");
		mav.addObject("jsonString", jsonString);
		return mav;
	}
}
